<?php
/* $Id$ */
/*
    squid_history.php
	Copyright (C) 2009 Wang Zhongliang <wzlsh629@163.com>.
	All rights reserved.

    Copyright (C) 2004, 2005 Scott Ullrich
    All rights reserved.

    Originally part of m0n0wall (http://m0n0.ch/wall)
    Copyright (C) 2003-2004 Manuel Kasper <mk@neon1.net>.
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:

    1. Redistributions of source code must retain the above copyright notice,
       this list of conditions and the following disclaimer.

    2. Redistributions in binary form must reproduce the above copyright
       notice, this list of conditions and the following disclaimer in the
       documentation and/or other materials provided with the distribution.

    THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
    INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
    AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
    AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
    oR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
    SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
    INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
    CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    POSSIBILITY OF SUCH DAMAGE.
*/

##|+PRIV
##|*IDENT=page-system-login/logout
##|*NAME=System: Login / Logout page
##|*DESCR=Allow access to the 'System: Login / Logout' page.
##|*MATCH=index.php*
##|-PRIV


## Load Essential Includes
require_once('guiconfig.inc');

$page_size = 100;

$group_descr = array('ip' => '局域网IP', 'domain' => '访问域名', 'hour' => '时段');
$sort_descr = array('tsize' => '流量', 'treq_count' => '请求数', 'ttext_count' => '页面数');

$db = sqlite_open('/var/db/web_access.db');

$date = $_GET['date'] ? $_GET['date'] : date('Y-m-d');
$hour = is_numeric($_GET['hour']) ? $_GET['hour'] : 'all';
$ip = $_GET['ip'] ? $_GET['ip'] : 'all';
$group = array_key_exists($_GET['group'], $group_descr) ? $_GET['group'] : 'ip';
$sort = array_key_exists($_GET['sort'], $sort_descr) ? $_GET['sort'] : '';
$domainname = $_GET['domainname'];
$domainfilter = $_GET['domainfilter'];

$page = (int)$_GET['page'];
if($page <= 0)
    $page = 1;
$offset = ($page - 1) * $page_size;

if($db !== false)
{
	$sql = "select min(date) from web_access_stat limit 1";
	$res = sqlite_query($db, $sql);
	if(sqlite_num_rows($res) > 0)
	{
		$dates = array();
		$start = strtotime(substr(sqlite_fetch_single($res), 0, 10));
		$end = time();
		while($start <= $end)
		{
			$dates[] = date('Y-m-d', $start);
			$start += 24 * 3600;
		}
		$hours = array(
		  '00:00', '01:00', '02:00', '03:00', '04:00', '05:00', '06:00', '07:00', '08:00', '09:00', '10:00', '11:00',
		  '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00', '21:00', '22:00', '23:00', 
		);
		
		$ips = array();
		$sql = "select distinct(ip) as ip from web_access_stat";
		$res = sqlite_query($db, $sql);
		while(($r = sqlite_fetch_array($res)))
		{
			$ips[] = $r[0];
		}

        if(!empty($domainname))
            $group = 'full_domain'; 		
		
		$sql = 'select date,hour,ip,name,';
		if(!empty($domainname))
		    $sql .= "full_domain as ";
		$sql .= 'domain,sum(size) tsize,sum(req_count) as treq_count,sum(text_count) as ttext_count from web_access_stat where 1 ';
		if($date != 'all')
		    $sql .= "and date = '" . sqlite_escape_string($date) . "' ";
        if($hour != 'all')
            $sql .= "and hour = " . (int)$hour . " ";
        if($ip != 'all')
            $sql .= "and ip = '" . sqlite_escape_string($ip) . "' ";
        if(!empty($domainfilter))
            $sql .= "and full_domain like '%" . sqlite_escape_string($domainfilter) . "%' ";
        if(!empty($domainname))
            $sql .= "and domain = '" . sqlite_escape_string($domainname) . "' ";
            
        $sql .= "group by $group ";
        if($sort)
        {
        	$sql .= "order by $sort desc";
        }
        else
        {
        	$sql .= "order by $group";
        }

        if(!empty($domainname))
            $group = 'domain';     

        $res = sqlite_query($db, $sql, SQLITE_ASSOC);
        $items = sqlite_fetch_all($res);
        
        $item_count = count($items);
        $page_total = ceil($item_count / $page_size);
        
        $items = array_slice($items, $offset, $page_size);
	}
	sqlite_close($db);
}

if($group == 'ip')
    $client = get_client_by_time($date, $hour);


$pgtitle = array("WEB代理", "上网记录");
$pgmenu = array('webproxy', '/squid_history.php');
include("head.inc");
?>

<body link="#0000CC" vlink="#0000CC" alink="#0000CC" onLoad="enablechange();">
<script language="JavaScript">
<!--
function enablechange() {
}
//-->
</script>
<?php
include("fbegin.inc");
?>
<div class="soft_cont_right_table">
<form name="iform" action="squid_history.php" method="get">
<table width="100%" border="0" cellpadding="0" cellspacing="0">
   <tr><td class="tabnavtbl">
<?php
    $tab_array = array();
    $tab_array[0] = array("一般设置", false, "/pkg_edit.php?xml=squid.xml&id=0");
    $tab_array[1] = array("代理设置", false, "/pkg_edit.php?xml=squid_upstream.xml&id=0");
    $tab_array[2] = array("缓存管理", false, "/pkg_edit.php?xml=squid_cache.xml&id=0");
    $tab_array[3] = array("访问控制", false, "/squid_nac.php");
    $tab_array[4] = array("流量管理", false, "/pkg_edit.php?xml=squid_traffic.xml&id=0");
    $tab_array[5] = array("上网记录", true, "/squid_history.php");
//    display_top_tabs($tab_array);
?>  
  </td>
  </tr>
</table>
<div id="mainarea">
<table class="tabcont" width="100%" border="0" cellpadding="6" cellspacing="0">
      <tr valign="top">
        <td class="vncell" colspan="<?php echo $group=='ip' ? 6 : ($group=='domain' ? 5 : 4);?>">
              日期：
	        <select name="date">
		        <option value="all">全部</option>
		        <?php foreach($dates as $key => $value): ?>
		        <option value="<?=$value;?>" <?php if($date==$value)echo 'selected';?>><?=$value;?></option>
		        <?php endforeach; ?>
	        </select>
	         时段：
            <select name="hour">
                <option value="all">全部</option>
                <?php foreach($hours as $key => $value): ?>
                <option value="<?=$key;?>" <?php if(is_numeric($hour) && $hour==$key)echo 'selected';?>><?=$value;?></option>
                <?php endforeach; ?>
            </select>
              局域网IP：
            <select name="ip">
                <option value="all">全部</option>
                <?php foreach($ips as $key => $value): ?>
                <option value="<?=$value;?>" <?php if($ip==$value)echo 'selected';?>><?=$value;?></option>
                <?php endforeach; ?>
            </select><br>
              按
            <select name="group">
                <option value="ip" <?php if($group=='ip')echo 'selected';?>>局域网IP</option>
                <option value="domain" <?php if($group=='domain')echo 'selected';?>>访问域名</option>
                <option value="hour" <?php if($group=='hour')echo 'selected';?>>时段</option>
            </select> 查看
              按
            <select name="sort">
                <option value="">默认方式</option>
                <option value="tsize" <?php if($sort=='tsize')echo 'selected';?>>流量</option>
                <option value="treq_count" <?php if($sort=='treq_count')echo 'selected';?>>请求数</option>
                <option value="ttext_count" <?php if($sort=='ttext_count')echo 'selected';?>>页面数</option>
            </select> 排序
              域名过滤 <input type="text" name="domainfilter" value="<?=htmlspecialchars($domainfilter);?>">
            <input type="submit" value="查看">
        </td>
      </tr>
      <tr>
        <td class="vncell"><?=$group_descr[$group];?></td>
        <?php if($group=='ip'):?>
        <td class="vncell">主机名称</td>
        <td class="vncell">认证用户</td>
        <?php elseif($group=='domain'):?>
        <td class="vncell"></td>
        <?php endif; ?> 
        <td class="vncell">流量</td>
        <td class="vncell">请求数</td>
        <td class="vncell">页面数</td>
      </tr>
      <?php foreach($items as $key => $value): ?>
      <?php
      $en_domainfilter = urlencode($domainfilter);
      ?>
      <tr>
        <td class="vtable">
        <?php
        if($group=='hour') 
            echo "<a href='squid_history.php?&date=$date&hour={$value[$group]}&ip=$ip&group=ip&sort=$sort&domainfilter=$en_domainfilter'>", $hours[$value[$group]], "</a>"; 
        else if($group=='ip')
            echo "<a href='squid_history.php?&date=$date&hour=$hour&ip={$value[$group]}&group=domain&sort=$sort&domainfilter=$en_domainfilter'>", $value[$group], "</a>";
        else if($group=='domain')
        {
            if(!empty($domainname))
            {
                echo $value[$group];
                $en_domain = urlencode($value[$group]);
            }
            else
            {
                $en_domain = urlencode($value[$group]);
                echo "<a href='squid_history.php?&date=$date&hour=$hour&ip=$ip&group=domain&sort=$sort&domainname=$en_domain&domainfilter=$en_domainfilter'>", $value[$group], "</a>";
            }
        }
        ?>
        </td>
        <?php if($group=='ip'):?>
        <td class="vtable"><a target="_blank" href="/client_stat.php?date=<?=$date;?>&hour=<?=$hour;?>&ip=<?=$value[$group];?>"><?=$client[$value[$group]]['nbtname'] ? $client[$value[$group]]['nbtname'] : $client[$value[$group]]['dhcpname'];?></a></td>
        <td class="vtable"><a target="_blank" href="/client_stat.php?date=<?=$date;?>&hour=<?=$hour;?>&ip=<?=$value[$group];?>"><?=$client[$value[$group]]['cpname'] == 'unauthenticated' ? '匿名' : $client[$value[$group]]['cpname'];?></a></td>
        <?php elseif($group=='domain'):?>
        <td class="vtable"><a href="<?php echo "squid_history.php?&date=$date&hour=$hour&ip=all&group=ip&sort=$sort&domainfilter=$en_domain"; ?>" title="访问过该域名的局域网IP地址">查看IP</a></td>        
        <?php endif; ?>
        <td class="vtable"><?=$value['tsize'];?></td>
        <td class="vtable"><?=$value['treq_count'];?></td>
        <td class="vtable"><?=$value['ttext_count'];?></td>
      </tr>
      <?php endforeach; ?>
      <?php if($page_total > 1): ?>
      <tr>
        <td class="vncell" align="center" colspan="<?php echo $group=='ip' || $group=='domain' ? 5 : 4;?>">
        <?php
            
            $en_domain = urlencode($domainname);
            foreach(range(1, $page_total) as $p)
            {
                if($page == $p)
                    echo $p;
                else
                    echo "<a href='squid_history.php?&date=$date&hour=$hour&ip=$ip&group=$group&sort=$sort&domainname=$en_domain&domainfilter=$en_domainfilter&page=$p'>$p</a>&nbsp;";
            }
        ?>
        </td>
      </tr>
      <?php endif; ?>
</table>
</div>
</form>
</div>
<?php include("fend.inc"); ?>

</body>
</html>